package com.leyou.item.service;


import com.leyou.item.mapper.AreaMapper;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.mapper.CityMapper;
import com.leyou.item.mapper.ProvinceMapper;
import com.leyou.item.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ProvinceMapper provinceMapper;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private AreaMapper areaMapper;

    public List<Category> queryCategoryListByParentId(Long id) {
        Category category = new Category();
        category.setParentId(id);
        return this.categoryMapper.select(category);
    }

    public List<Category> queryByBrandId(Long bid) {
        List<Category> categories = categoryMapper.queryByBrandId(bid);
        return categories;
    }

    public List<String> queryNamesByIds(List<Long> ids) {
        List<Category> categories = this.categoryMapper.selectByIdList(ids);
        ArrayList<String> list = new ArrayList<>();
        categories.forEach(category -> {
            list.add(category.getName());
        });
        return list;
    }


    public List<Category> queryAllCategoryByCid3(@RequestParam("id") Long id) {
        Category c3 = this.categoryMapper.selectByPrimaryKey(id);
        Category c2 = this.categoryMapper.selectByPrimaryKey(c3.getParentId());
        Category c1 = this.categoryMapper.selectByPrimaryKey(c2.getParentId());
        return Arrays.asList(c1, c2, c3);
    }

    public List<Province> queryProvin() {
        List<Province> provinces = provinceMapper.selectAll();
        return provinces;

    }

    public List<City> queryCity() {
        List<City> cities = cityMapper.selectAll();
        return cities;
    }

    public List<Area> queryArea() {
        List<Area> areas = areaMapper.selectAll();
        return areas;
    }

    /**
     * 根据id查询分类
     *
     * @param id
     * @return
     */
    public Category queryCategoryById(Long id) {

        return this.categoryMapper.selectByPrimaryKey(id);
    }

    public List<Cate> queryCategoryListByPid(Long pid) {
        List<Cate> cates = new ArrayList<>();
        Category record = new Category();
        record.setParentId(pid);
        List<Category> list1 = this.categoryMapper.select(record);
        list1.forEach(category -> {
            Cate cate = new Cate();
            cate.setId(category.getId());
            cate.setName(category.getName());
            if (category.getIsParent()){
                cate.setList(queryCategoryListByPid(cate.getId()));
            }
            cates.add(cate);
        });

        return cates;
    }
}
